package org.custom.spring.boot.security.config.security;

import org.cleaver.spring.utils.servlet.ServletUtil;
import org.custom.spring.boot.constant.Code;
import org.custom.spring.boot.constant.Message;
import org.custom.spring.boot.entity.Result;
import org.custom.spring.boot.security.exceptions.TokenExpireException;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * 处理用户的认证异常信息
 *
 * @author LiKun
 * @date 2021/11/8 18:34
 */
@Component
public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static Result<String> judgementExceptionAndDeal(Class<? extends AuthenticationException> exceptionClass) {
        Result<String> result = null;

        if (LockedException.class.equals(exceptionClass)) {
            result = new Result<>(Code.ACCOUNT_NOT_ENABLE, Message.ACCOUNT_LOCKED);
        } else if (DisabledException.class.equals(exceptionClass)) {
            result = new Result<>(Code.ACCOUNT_NOT_ENABLE, Message.ACCOUNT_NOT_ENABLE);
        } else if (TokenExpireException.class.equals(exceptionClass)) {
            result = new Result<>(Code.TOKEN_TIMEOUT, Message.TOKEN_TIMEOUT);
        } else if (AccountExpiredException.class.equals(exceptionClass)) {
            result = new Result<>(Code.ACCOUNT_NOT_ENABLE, Message.ACCOUNT_ID_EXPIRED);
        } else if (CredentialsExpiredException.class.equals(exceptionClass)) {
            result = new Result<>(Code.TOKEN_TIMEOUT, Message.TOKEN_TIMEOUT);
        } else if (InsufficientAuthenticationException.class.equals(exceptionClass)) {
            result = new Result<>(Code.USER_NOT_LOGIN, Message.USER_NOT_LOGIN);
        }

        return Optional.ofNullable(result).orElse(Result.fail());
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        exception.printStackTrace();
        ServletUtil.write(HttpAuthenticationEntryPoint.judgementExceptionAndDeal(exception.getClass()), response);
    }
}
